package com.drama.outtake.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.drama.outtake.MyException;
import com.drama.outtake.common.Result;
import com.drama.outtake.dao.UserDao;
import com.drama.outtake.domain.User;
import com.drama.outtake.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * @Author : 李先均
 * @Date 2023/3/4 22:08
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {
    private final IUserService userService;
    private final UserDao userDao;

    //todo 权限检查
    @PutMapping
    public Result<User> updateUserInfo(@RequestBody User user) {
        log.info("(put):/user,receive parameters = {}", JSON.toJSON(user));
        StpUtil.checkLogin();
        if (!user.getPhone().equals(StpUtil.getLoginIdAsLong())) {
            throw new MyException("无权修改该用户信息");
        }
        checkData(user);
        return Result.ok(userService.updateUserInfo(user));
    }

    private void checkData(User user) {
        if (user == null || user.getId() == null) {
            throw new MyException("传入参数错误");
        }
    }

    //TODO
    @GetMapping("/{id}")
    public Result<User> getUserInfo(@PathVariable("id") Long id) {
        log.info("(get):/user/{}", id);
        boolean exists = userDao.existsById(id);
        if (!exists) return Result.fail("用户不存在！");
        User user = userDao.getById(id);
        StpUtil.checkLogin();
        return Result.ok(user);
    }
}
